<?php

namespace app\api\service\alipay;

use app\admin\model\Rechargerecord;

use think\Db;
use think\Exception;

class RechargePay extends BasePay
{
    public function pay($param)
    {
        if (empty($param->total_fee)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '充值金额未接收');
        }
        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '用户Id未接收');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '支付类型未接收');
        }
        if (!in_array($param->type, [1, 2])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '支付方式(type) 不正确');
        }

        Db::startTrans();
        // 创建订单
        $data['record_money'] = $param->total_fee;
        $data['member_id'] = $param->memberId;
        $data['pay_method'] = $param->type;
        $data['order_no'] = create_order_sn();
        $data['gift_money'] = $param->gift_money;
        $data['type'] = 1;
        $data['detail'] = '充值 ¥' . $data['record_money'] / 100;

        $result = Rechargerecord::create($data, true);
        if ($result === false) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '创建订单失败');
        }

        if ($param->type == 2) {
            // 调用支付宝支付
            $body = '充值支付';
            $subject = '充值支付';
            $notify_url = config('alipay.recharge_pay_back_url');
            $result = $this->run($body, $subject, $data['order_no'], $data['record_money'], $notify_url);

            return show(config('status.SUCCESS_STATUS'), 'ok', $result);
        } else if ($param->type == 1) {
            // 微信支付
        } else {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '错误的请求!');
        }
    }
}